import React from 'react'
// ===================================================================== Temp
import SearchForm from '#cpt/temp/SearchForm'
import Table from '#cpt/temp/Table'
import Controls from '#cpt/temp/Controls'
import TableControls from '#cpt/temp/TableControls'
import Confirm from '#cpt/temp/Confirm'
import Tabs from '#tp/tabs/tabs'
// ===================================================================== global declare
const { $fn, $http, $Lazy, globalConfig } = window
const { COVIDUrl } = globalConfig
// ===================================================================== $Lazy
const Printer 			= $Lazy.hook(()=>import('#private/printer'))
const Page 				= $Lazy.load(()=>import('#tp/page/page-container'))
const BtnGroup 			= $Lazy.load(()=>import('#tp/btn-group'))
const $cache 			= $Lazy.file(()=>import('#private/cache-api'))
const $time 			= $Lazy.file(()=>import('@com/utils/time'))
// ===================================================================== data
const AuditStatus = [{ name:'全部', value:-99 },{ name:'待审核', value:0 },{ name:'已审核', value:1 },{ name:'已作废', value:-1 }]

const tabsData = [{ title:'全部', status:-99},{ title:'待审核', status:0},{ title:'已审核', status:1},{ title:'已作废', status:-1}]
// ===================================================================== component
class Index extends React.Component{
	state={
		data:[],
		pag: {},
		selectedKeys:[],
		selectedRows:[],
		// 搜索表单列表
		forms: [
			{ label: '条码号',		name: 'spec_code' },
			{ label: '实验号',		name: 'experiment_num' },
			{ label: '医院名称',		name: 'hosp_id',		type: 'select', 	loading:true,	idStr:'uuid',	nameStr:'hospName' },
			{ label: '板号',			name: 'board_no' },
			{ label: '接收时间',		names: ['check_time_start','check_time_end'], 	type:'date-range', name: 'jz-time'  },
		],
		
	}
	model = {}
	kindName = ''
	
	componentDidMount(){
		this.index = $fn.local('xgxt-bbjs-index') || 0
		this.status = tabsData[this.index]['status']
		this.getSelect()
		$fn.fresh.on(() => this.fetch() )
	}
	
	componentWillUnmount(){
		$fn.fresh.remove()
		$fn.remove('xgxt-bbjs-index')
	}
	
	onTime = reset => {
		$time.then(f=>{
			const arr = f.duration['2-9-now']()
			this.resetModel = { check_time_start: arr[0], check_time_end: arr[1], 'jz-time':arr }
			this.model = $fn.copy(this.resetModel)
			this.fetch()
		})
	}
	
	// 获取下拉数据
	getSelect = () => {
		const { forms } = this.state
		
		return $cache.then( async f => {
			// 医院
			this.hostData = await f.getCache({ api:COVIDUrl+'Hospital/query',param:{page:1,page_num:10000,status:1} })
			$fn.setRow( forms, 'hosp_id',  this.hostData)
			//
			this.setState({ forms })
			this.onTime()
		})
	}

	// paging
	fetch = () => $fn.fetch.call(this,COVIDUrl+'codeinfo/query', { param:{status:this.status}, COVID:true })
		
	// 表格数据
	cols = [
		{ title: '标本条码', 	dataIndex: 'specCode',  			width:130  },
		{ title: '实验号', 		dataIndex: 'experimentNum', 		width:100  },
		{ title: '录入时间', 	dataIndex: 'createdAt',  			...$fn.table.time },
		{ title: '医院', 		dataIndex: 'hospId', 				width:200,		render: text => $fn.getState(this.hostData,text,'hospName','uuid') },
		{ title: '板号', 		dataIndex: 'boardNo', 				width:100  },
		{ title: '接收时间', 	dataIndex: 'checkTime',  			...$fn.table.time },
		{ title: '状态', 		dataIndex: 'status', 			 	width:100,		render: text => $fn.getState(AuditStatus,text) },
		{ title: '备注', 		dataIndex: 'remark', 			 	width:200 },
		TableControls.controls.call(this,{ width: 60 })
	]
	table_controls = ({uuid, status}) => {
		return [
			+status === 0 && Confirm.call(this, '审核', COVIDUrl+'codeinfo/status', { query:{status:1,uuids:uuid} }),
			+status === -1 && Confirm.call(this, '恢复', COVIDUrl+'codeinfo/status', { query:{status:0,uuids:uuid} }),
		]
	}
	
	// 操作按钮
	controls = () => {
		const { selectedKeys } = this.state
		const uuids = selectedKeys.join(',')
		return [
			Controls.pushTo.call(this, '录入样本', `project-enter`, {code: 'F1'} ),
			Confirm.call(this, '批量审核', COVIDUrl+'codeinfo/status', { code: 'F3', isKeys:1, query:{status:1,uuids} }),
			Confirm.call(this, '批量作废', COVIDUrl+'codeinfo/status', { isKeys:1, query:{status:-1,uuids} }),
			(+this.status===-1||+this.status===-99) && Confirm.call(this, '批量恢复', COVIDUrl+'codeinfo/status', { isKeys:1, query:{status:0,uuids} }),
			Controls.click.call(this, '打印实验号', ()=>{
				if(this.kindName){
					this.printNum()
				}else{		//获取项目名称
					$http.pull(null, COVIDUrl+'settings/query', { param:{page_num:1000,page:1 }}).then(data=>{
						if($fn.hasArray(data)){
							const kindItem = data.find(v => v.settingsCode === 'ConvidProjectName')
							this.kindName = kindItem ? kindItem.settingsValue : ''
							this.printNum()
						}
					})
				}
			}, {isKeys:1} ),
			Controls.click.call(this,'导出', ()=>{
				const param = {...this.model,status:this.status}
				$http.submit(null, COVIDUrl+'codeinfo/download', { param }).then((data)=>{
					if(data){
						window.open(`${COVIDUrl}download?rand=${data}`)
					}
				})
			},{ghost:true})
		]
	}
	
	printNum = () => {		// 打印实验号
		const { selectedRows } = this.state
		let printData = []
		selectedRows.forEach(v => {
			v.specCode=v.specCode.replace(/(^\s*)|(\s*$)/g,"")
			const printInfo = {
				lb_tpl:v.experimentNum,
				spec_code:v.specCode,
				tpl_code: "barcode",
				kind_name:this.kindName,
				job_id: "感染性核酸岗"
			}
			printData.push(printInfo)
		})
		this.printerRef.printer({ code: 50104, data:printData, loading:false})
	}
	
	render(){
		return (
			<>
				<Page title='' >
					<div className='fxmj'>
						<Tabs
							data={ tabsData } defaultActiveKey = { $fn.local('xgxt-bbjs-index') || 0 }
							onTabs = { ({ status },index) => {
								this.status = status
								this.setState({data:[]})
								this.fetch()
								$fn.local('xgxt-bbjs-index', index)
							}}
						/>
						<div><BtnGroup controls={this.controls()} /></div>
					</div>
					
					{/* 搜索 */}
					{ SearchForm.call(this, {timeStr:'2-9-now'}) }
					{/* 表格 */}
					{ Table.call(this) }
				</Page>
				{/* 打印 */}
				<Printer onRef = { ref => this.printerRef = ref } hasBtn = {false} />
			</>
		)
	}
}
export default Index